package javax.realtime;

public abstract class Clock {
	
	private static final RealTimeClock rtc = RealTimeClock.instance();
	
	public Clock()	{}
	
	public abstract RelativeTime getEpochOffset();
	public static Clock getRealtimeClock()
	{
		return rtc;
	}
	public abstract RelativeTime getResolution();
	public abstract AbsoluteTime getTime();
	public abstract AbsoluteTime getTime(AbsoluteTime dest);
	public abstract void setResolution(RelativeTime resolution);
	
	
	private static class RealTimeClock extends Clock
	{
		static RelativeTime resolution = null;
		private static final long period = 10;
		
		private static RealTimeClock instance()
		{
			long nanos = period * HighResolutionTime.NANOS_PER_MILLI;
			long millis = period;
			RealTimeClock clk = new RealTimeClock();
			resolution = new RelativeTime(millis, ((int)(nanos % HighResolutionTime.NANOS_PER_MILLI)), new RealTimeClock());
			return clk;
		}
		
		@Override
		public RelativeTime getEpochOffset() {
			return new RelativeTime(0,0,this);
		}

		@Override
		public RelativeTime getResolution() {
			return new RelativeTime(resolution);
		}

		@Override
		public AbsoluteTime getTime() {
			return getTime(new AbsoluteTime(0, 0, this));
		}

		@Override
		public AbsoluteTime getTime(AbsoluteTime dest) {
			if(dest != null)
			{
				long nanos = System.nanoTime();
				long millis = nanos / HighResolutionTime.NANOS_PER_MILLI;
				nanos = (nanos % HighResolutionTime.NANOS_PER_MILLI);
				dest.set(millis, (int)nanos);
				dest.clock = this;
			}
			return dest;
		}

		@Override
		public void setResolution(RelativeTime resolution) {
			throw new UnsupportedOperationException();
		}		
	}
}
